<?php
/**
 * 周舟 hzboye010@163.com
 * addby sublime snippets
 */
namespace Webview\Controller;

use Webview\Controller\WebViewController;
use Common\Api\ScoreGoodsApi;
use Admin\Api\MemberApi;
use Shop\Api\BannersApi;
use Common\Api\ExchangeLogApi;
use Admin\Api\AddressApi;
use Tool\Api\AreaApi;
use Tool\Api\CityApi;
use Tool\Api\ProvinceApi;
use Shop\Api\WalletApi;
use Shop\Api\RedEnvelopeApi;
use Shop\Api\CouponApi;

class ScoreGoodsController extends WebviewController{
    /**
     * 初始化
     */
    public function _initialize(){
        parent::_initialize();
        // $this->assign('isapp','com.itboye.sunsun://TYPE=SGOODS_DETAIL');

        // $this->assign('isapp1','com.itboye.sunsun://TYPE=MORE_SCORE');
        // $this->assign('isapp2','com.itboye.sunsun://TYPE=SHOW_LOG');
        // $this->assign('isapp','');
    }
    /**
     * 积分商城页面入口
     */
    public function index(){
      $uid = $this->uid;
      $psize = 999;//4;
      $r = apiCall(MemberApi::GET_INFO,array(array('uid'=>$uid)));
      if(!$r['status']) $this->error($r['info']);
      $score = $r['info']['score'];
      $this->assign('score',$score);
      $this->assignTitle('积分商城');
      //banner code:scoreshop_index
      $r = apiCall(BannersApi::GET_INFO,array(array('position'=>C('DATATREE.BANNER_SCORESHOP_INDEX'))));
      if(!$r['status']) $this->error($r['info']);
      $this->assign('banner',$r['info']?$r['info']['img']:0);
      //最新的1页 with count
      $info = $this->getSGoods(0,$psize,'new');
      // dump($this->groupByPage($info['list'],4));exit;
      $this->assign('sgoods_new',$this->groupByPage($info['list'],4));
      $this->assign('new_p',ceil(intval($info['count'])/4));
      // $this->assign('new_c',intval($info['count']));
      //限购的1页 with count
      $info =  $this->getSGoods(0,$psize,'limit');
      $this->assign('sgoods_limit',$this->groupByPage($info['list']),4);
      $this->assign('limit_p',ceil(intval($info['count'])/4));
      $this->display('ScoreShop:index');
    }

    private function groupByPage($list,$psize){
      $r = array();
      $c = count($list);
      for ($i=0; $i < $c; $i++) {
        $r[floor($i/$psize)][] = $list[$i];
      }
      return $r;
    }
    /**
     * ajax获取积分商品
     * @param  int      the start position
     * @param  int      pagesize
     * @return [json]
    */
    public function getSGoods($start,$size,$type='new'){
      if($type=='new'){
        $r = apiCall(ScoreGoodsApi::QUERY,array(null,$start,$size));
      }elseif($type='limit'){
        $r = apiCall(ScoreGoodsApi::QUERY,array(array('_string'=>'buy_limit>0'),$start,$size));
      }else{
        $this->apiReturnErr('类型错误');
      }
      if(!$r['status'])  $this->apiReturnErr($r['info']);
      foreach ($r['info']['list'] as &$v) {
        $v['url'] = U('ScoreGoods/detail',array('uid'=>$this->uid,'psw'=>$this->psw,'pid'=>$v['id']));
      }
      return $r['info'];
    }

    // public function test(){
    //     // echo json_encode(apiCall(GameApi::TEST,array($uid,$gid)));
    //     echo '---';
    // }

    /**
     * 商品详情查看
     */
    public function detail() {
      if (IS_GET) {
        $token  = md5(time());
        session('paycheck',$token);
        $id    = I('get.pid', 0);

        $r = apiCall(ScoreGoodsApi::GET_INFO,array(array('id'=>$id)));
        // dump($r);exit;
        if(!$r['status']) $this->error($r['info']);
        if(empty($r['status'])) $this->error('pid错误');
        if(empty($r['info']['detail']))   $r['info']['detail']   = '暂无商品描述';
        if(empty($r['info']['synopsis'])) $r['info']['synopsis'] = '暂无兑换说明';
        // dump($r['info']);exit;
        $this -> assign ('entry',$r['info']);
        $type = intval($r['info']['type']);
        $tpl_id = intval($r['info']['tpl_id']);
        if(!in_array($type,array(2,3)) && $tpl_id){
          $post_price = $tpl_id;
        }else{
          $post_post = 0;
        }
        $this->assign('post_price',$post_price);
        $this->assign('price',floatval($r['info']['price'])+$post_price);
        $this -> assignTitle($r['info']['name'].'-兑换详情');
        $this -> assign ('paycheck',$token);
        $this -> display('ScoreShop:detail');
      }
    }
    public function getArea($cid=1017,$type=1){
        $cid  = intval($cid);
        $type = intval($type);
        if($type === 2)
          $r = apiCall(AreaApi::GET_LIST_BY_CITY_ID,array($cid));
        elseif($type === 1)
          $r = apiCall(CityApi::GET_LIST_BY_PROVINCE_ID,array($cid));
        // elseif($type === 1)
        //   $r = apiCall(ProvinceApi::QUERY_NO_PAGING,array());
       echo json_encode($r);

    }
    public function getPayUrl($id){
      $aid  = I('addressid');
      $type = I('pay','000');
      $uid  = $this->uid;
      $isPay = false;
      if($type != '000' && strlen($type)===3){
        $isPay = true;
        //支付URL
        $wallet = intval($type[2]);
        $alipay = intval($type[0]);
        $wxpay  = intval($type[1]);
      }
      //收货地址检查
      $r = apiCall(AddressApi::GET_INFO,array(array('id'=>$aid,'uid'=>$uid)));
      // dump($r);exit;
      if(!$r['status']) $this->apiReturnErr($r['info']);
      if(empty($r['info'])) $this->apiReturnErr('地址ID或用户ID错误');
      //兑换记录查询
      $map = array();
      $r2 = apiCall(ExchangeLogApi::GET_INFO,array(array('id'=>$id,'uid'=>$uid)));
      if(!$r2['status']) $this->apiReturnErr($r2['info']);
      if(empty($r2['info'])) $this->apiReturnErr('兑换记录ID错误');
      if($r2['info']['price'] == 0) $map['exchange_status'] = 0;

      $pay_balance = floatval($r2['info']['pay_balance']);
      $ex_type     = intval($r2['info']['type']);
      $ex_tpl_id   = intval($r2['info']['tpl_id']);
      $price       = floatval($r2['info']['price']) - $pay_balance;
      if($price == 0) $map['exchange_status'] = 0;
      if($price <0 ) $this->apiReturnErr('兑换记录错误');

      $model = M();
      $model->startTrans();
      if($isPay){
        //需要支付
        if($wallet){
          //查询用户可用余额
          $r2 = apiCall(WalletApi::GET_INFO,array(array('uid'=>$uid)));
          if(!$r2['status']) $this->apiReturnErr($r2['info']);
          if(1 === intval($r2['info']['wallet_type'])) $this->apiReturnErr('账户余额冻结中');
          $money = floatval($r2['info']['account_balance']) - floatval($r2['info']['frozen_funds']);

          if($money<=0) $this->apiReturnErr('余额不足');
          if($money<$price){
            //部分支付
            if(0 == $wxpay && 0==$alipay) $this->apiReturnErr('余额不足以支付');
            $price = $price - $money;
            //余额减少$money + 并记录余额变动
            $r = apiCall(WalletApi::MINUS,array($uid,$money,getDataTree('WALLET_PAY_SGOODS'),'余额支付'));
            if(!$r['status']){
              $model->rollback();
              $this->apiReturnErr($r['info']);
            }
            $map['pay_balance'] = $pay_balance+$money; //已支付余额
          }else{
            //全额支付
            //余额减少$price + 并记录余额变动
            $r = apiCall(WalletApi::MINUS,array($uid,$price,getDataTree('WALLET_PAY_SGOODS'),'余额支付'));
            if(!$r['status']){
              $model->rollback();
              $this->apiReturnErr($r['info']);
            }

            $map['exchange_status'] = 0; //兑换支付完成
            $map['pay_balance'] = $pay_balance+$price; //已支付余额
            $price = 0; //待支付款项
            if(in_array($ex_type,array(2,3))){
              //发送虚拟奖品 并 推送
              $msg = '支付成功，请耐心等待工作人员发货！';
              if($ex_type === 2){
                //发放红包 + 推送
                $r = apiCall(RedEnvelopeApi::SEND_TO_USER,array($uid,$ex_tpl_id,'红包[萌币兑换]',0,0,true));
                if(!$r['status']){
                  $model->rollback();
                  return $this->apiReturnErr($r['info']);
                }
                $msg = '红包发放成功，请前往百宝箱查看！';
              }elseif($ex_type === 3){
                //发放优惠券 + 推送
                $r = apiCall(CouponApi::SEND_TO_USER,array($uid,$ex_tpl_id,'优惠券[萌币兑换]',0,0,true));
                if(!$r['status']){
                  $model->rollback();
                  return $this->apiReturnErr($r['info']);
                }
                $msg = '优惠券发放成功，请前往百宝箱查看！';
              }
              $map['exchange_status'] = 1;
            }else{
              //实物 - 待发货
              $msg = '支付成功，请耐心等待工作人员发货！';
            }
            $back_url = C('SITE_URL').U('ExchangeLog/payback',array('uid'=>$uid,'psw'=>$this->psw,'id'=>$id,'info'=>$msg));
            $map['pay_status']      = 1; //已发货状态
          }
        }
        if($price>0){
          //需要第三方支付
          $ptype = 0;
          if($alipay) $ptype=1;
          if($wxpay)  $ptype=2;
          $r = apiCall(ScoreGoodsApi::GET_PAY_URL,array($uid,$price,$this->psw,$ptype));
          if(!$r['status']) $this->apiReturnErr($r['info']);
          $back_url = $r['info']['url'];
        }
      }
      unset($r2);
      $map['address_id']       = $aid;
      $map['address_province'] = $r['info']['province'];
      $map['address_city']     = $r['info']['city'];
      $map['address_area']     = $r['info']['area'];
      // dump($map);exit;
      $r = apiCall(ExchangeLogApi::SAVEBYID,array($id,$map));
      if(!$r['status']) $model->rollback();
      else $model->commit();
      $r['back_url'] = $back_url;
      echo json_encode($r);
      exit;
    }

  public function addressadd(){
      // $get = I('get.');
      // dump($get);
      $map = I('post.');
      // dump($map);exit;
      // if(!$map['info']['catid']) exit('非法地区信息');
      if(!$map['provinceid']) exit('错误省份');
      if(!$map['cityid'])     exit('错误城市');
      if(!$map['areaid'])     exit('错误地区');
      if(!$map['detailinfo']) exit('错误地址');
      if(!$map['postal_code'] || !preg_match('/^\d{6}$/',$map['postal_code'])) exit('错误邮编');
      if(!$map['mobile'] || !preg_match('/^1\d{10}$/',$map['mobile'])) exit('错误手机号');
      if(!$map['contactname']) exit('错误联系人');
      $map['uid'] = $this->uid;
      $map['country'] = '中国';
      $map['id_card'] = '';
      $r = apiCall(AddressApi::ADD,array($map));
      if(!$r['status']){
        $this->apiReturnErr('address add error');
      }else{
        $id = intval($r['info']);
        // echo 'id'.$id;
        $r = apiCall(AddressApi::GET_INFO,array(array('id'=>$id)));
        echo json_encode($r);
      }
      exit;
  }

  public function exchange($pid){
    //返回错误信息 或 正确跳转地址
    echo json_encode(apiCall(ScoreGoodsApi::EXCHANGE,array($this->uid,$this->psw,$pid)));
  }

  public function apiReturnSuc($info){
    echo json_encode(array('status'=>true,'info'=>$info));exit;
  }
  public function apiReturnErr($info){
    echo json_encode(array('status'=>false,'info'=>$info));exit;
  }
}